package com.ruoyi.article.service.impl;

import java.text.Collator;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.ArticleCategory.domain.ArticleCategory;
import com.ruoyi.ArticleCategory.mapper.ArticleCategoryMapper;
import com.ruoyi.articleUpvote.domain.ArticleUpvote;
import com.ruoyi.comment.domain.Comment;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.ruoyi.article.mapper.ArticleMapper;
import com.ruoyi.article.domain.Article;
import com.ruoyi.article.service.IArticleService;

import javax.annotation.Resource;
import javax.xml.transform.Source;

/**
 * 文章管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-06
 */
@Service
public class ArticleServiceImpl implements IArticleService 
{
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ArticleCategoryMapper articleCategoryMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询文章管理
     * 
     * @param id 文章管理主键
     * @return 文章管理
     */
    @Override
    public Article selectArticleById(Integer id)
    {
//        Article article = redisCache.getCacheObject("article:list:"+id);
//        if (article != null){
//            return article;
//        }
//        article = articleMapper.selectArticleById(id);
//        redisCache.setCacheObject("article:list:"+id, article);
        return articleMapper.selectArticleById(id);
    }

    /**
     * 查询文章管理列表
     * 
     * @param article 文章管理
     * @return 文章管理
     */
    private static Integer total;
    @Override
    public List<Article> selectArticleList(Article article, String nickName, String categoryName)
    {
//        Collection<String> keys = redisCache.keys("article:list:*");
//        List<Article> articleList = new ArrayList<>();
//
//        if (keys == null || keys.isEmpty()){
//            System.out.println("查询数据库了！！！！！！！");
//            // 查询数据库中的文章，文章包含用户、文章分类
//            List<Article> articles = selectArticleAll();
//            if (articles == null || articles.isEmpty()){
//                // Redis和数据库中都没有一片文章
//                return null;
//            } else {
//
//                for (String key : keys) {
//                    articleList.add(redisCache.getCacheObject(key));
//                }
//                // 数据库中有文章,赋值给Redis集合并加入Redis缓存
//                articleList = articles;
//                for (Article article1 : articles) {
//                    redisCache.setCacheObject("article:list:"+article1.getId(),article1);
//                }
//            }
//        }
//        for (String key : keys) {
//            System.out.println("key:"+key);
//            articleList.add(redisCache.getCacheObject(key));
//        }
//
//        // 对文章集合进行筛选
//        articleList = articleList.stream().filter(articleStream -> articleStream.getDel() == 0).collect(Collectors.toList());
//        if (articleList == null || articleList.isEmpty()){
//            return null;
//        }
//
//
//        if (article.getTitle() != null && !article.getTitle().isEmpty()){
//            articleList = articleList.stream().filter(articleStream -> articleStream.getTitle().toLowerCase().contains(article.getTitle())).collect(Collectors.toList());
//            if (articleList == null || articleList.isEmpty()){
//                return null;
//            }
//        }
//        if (article.getDate() != null && !article.getDate().isEmpty()){
//            String date = article.getDate();
//            String[] split = date.split("to");
//
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//            LocalDateTime startTime = LocalDateTime.parse(split[0] + " 00:00", formatter);
//            LocalDateTime endTime = LocalDateTime.parse(split[1] + " 23:59", formatter);
//
//            articleList = articleList.stream().filter(articleStream -> {
//                        LocalDateTime currentDateTime = LocalDateTime.parse(articleStream.getDate(), formatter);
//                        return currentDateTime.isAfter(startTime) && currentDateTime.isBefore(endTime);
//                    })
//                    .collect(Collectors.toList());
//
//            if (articleList == null || articleList.isEmpty()){
//                return null;
//            }
//        }
//
//        if (nickName != null && !nickName.isEmpty()){
//            articleList = articleList.stream().filter(articleStream -> articleStream.getSysUser().getNickName().toLowerCase().contains(nickName)).collect(Collectors.toList());
//            if (articleList == null || articleList.isEmpty()){
//                return null;
//            }
//        }
//
//        if (categoryName != null && !categoryName.isEmpty()){
//            articleList = articleList.stream().filter(articleStream -> articleStream.getArticleCategory().getCategoryName().toLowerCase().contains(categoryName)).collect(Collectors.toList());
//            if (articleList == null || articleList.isEmpty()){
//                return null;
//            }
//        }
//        articleList.sort(Comparator.comparing(Article::getId));
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        List<Article> list = new ArrayList<>();
//        for (int i = 0; i < pageDomain.getPageSize(); i++){
//            if ((pageDomain.getPageNum()-1)*pageDomain.getPageSize()+i < articleList.size()){
//                list.add(articleList.get((pageDomain.getPageNum()-1)*pageDomain.getPageSize()+i));
//            }
//        }
//        this.total = articleList.size();
//        return list;

        Long userId = article.getUserId();
        if (userId == null){
            Long userId1 = SecurityUtils.getLoginUser().getUserId();
            if (userId1 != 1){
                article.setUserId(userId1);
            }
        } else {
            article.setUserId(null);
        }
        SysUser sysUser = new SysUser();
        ArticleCategory articleCategory = new ArticleCategory();

        if (nickName != null){
            sysUser.setNickName(nickName);
        } else {
            sysUser.setNickName(null);
        }

        if (categoryName != null){
            articleCategory.setCategoryName(categoryName);
        } else {
            articleCategory.setCategoryName(null);
        }

        String date = article.getDate();
        if (date != null && !"".equals(date)){
            String[] split = date.split("to");
            Map<String,Object> map = new HashMap<>();
            map.put("beginDate",split[0]);
            map.put("endDate",split[1]);
            article.setParams(map);
        }

        article.setSysUser(sysUser);
        article.setArticleCategory(articleCategory);

        return articleMapper.selectArticleList(article);

    }

    // 根据分类查询文章
    @Override
    public List<Article> selectArticleByCategoryId(Integer categoryId){
        List<Article> articles = selectArticleAll();
        return articles;
//        Collection<String> keys = redisCache.keys("article:list:*");
//        List<Article> articleList = new ArrayList<>();
//
//        if (keys == null || keys.isEmpty()){
//            System.out.println("查询数据库了！！！！！！！");
//            // 查询数据库中的文章，文章包含用户、文章分类
//            List<Article> articles = selectArticleAll();
//            System.out.println("asoihfuikashfuisa");
//            if (articles == null || articles.isEmpty()){
//                // Redis和数据库中都没有一片文章
//                return null;
//            } else {
//
//                for (String key : keys) {
//                    articleList.add(redisCache.getCacheObject(key));
//                }
//                // 数据库中有文章,赋值给Redis集合并加入Redis缓存
//                articleList = articles;
//                for (Article article1 : articles) {
//                    redisCache.setCacheObject("article:list:"+article1.getId(),article1);
//                }
//            }
//        }
//
//        for (String key : keys) {
//            articleList.add(redisCache.getCacheObject(key));
//        }
//        articleList = articleList.stream().filter(articleStream -> articleStream.getCategoryId() == categoryId).collect(Collectors.toList());
//        articleList.sort(Comparator.comparing(Article::getId));
//        return articleList;
    }


    // 给controller传递total
    @Override
    public Integer getTotal(){
        return this.total;
    }

// 查询文章详情
    @Override
    public Article selectArticleDetails(Integer articleId) {

        Article article = articleMapper.selectArticleDetails(articleId);

        return article;
//        Article articleRedis = redisCache.getCacheObject("article:details:" + articleId);
//        if (articleRedis == null){
//            Article article = articleMapper.selectArticleDetails(articleId);
//            if (article == null){
//                return null;
//            }
//            // 数据库有，加入Redis并返回
//            redisCache.setCacheObject("article:details:" + articleId, article);
//            return article;
//        }
//        return articleRedis;
    }

// 查询热门文章
    @Override
    public List<Article> selectHotArticleList(){
        return articleMapper.selectHotArticleList();
    }

// 根据文章标题模糊查询
    @Override
    public List<Article> selectArticleListByTitle(String title) {
        return articleMapper.selectArticleListByTitle(title);
    }

    /**
     * 新增文章管理
     * 
     * @param article 文章管理
     * @return 结果
     */
    @Override
    public int insertArticle(Article article)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        article.setUserId(loginUser.getUserId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = sdf.format(new Date());
        article.setDate(format);
        int num = articleMapper.insertArticle(article);

        //redisCache.setCacheObject("article:list:"+article.getId(),articleMapper.selectArticleDetails(article.getId()));
        return num;
    }

    /**
     * 修改文章管理
     * 
     * @param article 文章管理
     * @return 结果
     */
    @Override
    public int updateArticle(Article article)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String format = sdf.format(new Date());
        article.setDate(format);

//        redisCache.deleteObject("article:list:"+article.getId());
//        if (redisCache.getCacheObject("article:details:"+article.getId()) != null){
//            redisCache.deleteObject("article:details:"+article.getId());
//        }
        return articleMapper.updateArticle(article);
    }

    /**
     * 批量删除文章管理
     * 
     * @param ids 需要删除的文章管理主键
     * @return 结果
     */
    @Override
    public int deleteArticleByIds(Long[] ids)
    {
        return articleMapper.deleteArticleByIds(ids);
//        Collection<String> keys = redisCache.keys("article:list:*");
//
//            for (String key : keys) {
//                String num = key.substring(key.lastIndexOf(":") + 1);
//                for (Long id : ids) {
//                    if (num.equals(String.valueOf(id))){
//                        Article article = redisCache.getCacheObject(key);
//                        article.setDel(1);
//                        redisCache.setCacheObject(key,article);
//                        redisCache.setCacheObject("article:details:"+article.getId(),article);
//                    }
//                }
//            }
//        return 1;
    }

    /**
     * 删除文章管理信息
     * 
     * @param id 文章管理主键
     * @return 结果
     */
    @Override
    public int deleteArticleById(Long id)
    {
        return articleMapper.deleteArticleById(id);
//        Article article = redisCache.getCacheObject("article:list:" + id);
//        article.setDel(1);
//        redisCache.setCacheObject("article:list:" + id,article);
//        redisCache.setCacheObject("article:details:"+id,article);
//        return 1;
    }

    // 数据库查询所有文章
    @Override
    public List<Article> selectArticleAll(){
        Article article = new Article();

        SysUser sysUser = new SysUser();
        sysUser.setNickName(null);
        ArticleCategory articleCategory = new ArticleCategory();
        articleCategory.setCategoryName(null);

        article.setSysUser(sysUser);
        article.setArticleCategory(articleCategory);
        List<Article> articles = articleMapper.selectArticleList(article);
        return articles;
    }

    public Integer saveNum(Article article){
        return articleMapper.updateArticle(article);
    }
//        Article articleDetails = redisCache.getCacheObject("article:details:"+article.getId());
//        if (articleDetails == null){
//            System.out.println(article.getId());
//            articleDetails = articleMapper.selectArticleDetails(article.getId());
//        }
//
//        articleDetails.setUpvoteNum(article.getUpvoteNum());
//        articleDetails.setReadNum(article.getReadNum());
//
//        redisCache.setCacheObject("article:details:"+article.getId(),articleDetails);
//
//        return 1;
//    }
}
